package com.mic.current.pool.simple;

/**
 * Created by hy06 on 2018/2/22.
 */
public class Worker extends Thread{
    // 线程池
    private ThreadPool pool;

    // 任务
    private Runnable target;

    private boolean isShutDown = false;
    private boolean isIdle = false;

    public Worker(String name, ThreadPool pool, Runnable target) {
        super(name);
        this.pool = pool;
        this.target = target;
    }

    public Runnable getTarget() {
        return target;
    }

    public void setTarget(Runnable target) {
        this.target = target;
    }

    public boolean isIdle() {
        return isIdle;
    }

    public void setIdle(boolean idle) {
        isIdle = idle;
    }

    @Override
    public void run() {
        while (!isShutDown) {
            isIdle = false;
            if (target != null) {
                // 运行任务
                target.run();
            }
            // 任务结束
            isIdle = true;

            // 该任务结束后，不关闭线程，而是放入线程池空闲队列
            pool.repool(this);
            synchronized (this) {
                // 线程空间，等待新的任务到来
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            isIdle = false;
        }
    }
}
